//
//  UIColor+Extension.swift
//  DZYPageView
//
//  Created by dongzhenyu on 2017/7/7.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import UIKit

// 类扩展
extension UIColor {
    class func randomColor() -> UIColor {
        return UIColor(red: CGFloat(arc4random_uniform(256))/255.0, green: CGFloat(arc4random_uniform(256))/255.0, blue: CGFloat(arc4random_uniform(256))/255.0, alpha: 1.0)
    }
    
    // 遍历构造函数 1.必须加上convenience 2.必须调用self.init()原有的某一个函数
    // 构造函数是没有返回值的  系统会自动返回当前你创建的对象
    convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) {
        self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
    }
    
    // 16进制
    convenience init?(hexString: String) {
        
        // 1.判断字符串的长度是否大于等于6
        guard hexString.characters.count >= 6 else {
            return nil
        }
        
        // 2.将字符串转成大写
        var hexTempString = hexString.uppercased()
        
        // 3.判断字符串是否是 0X/##FF0022
        if hexTempString.hasPrefix("0X") || hexTempString.hasPrefix("##"){
            hexTempString = (hexTempString as NSString).substring(from: 2)
        }
        
        // 4.判断字符串是否是以#开头
        if hexTempString.hasPrefix("#") {
            hexTempString = (hexTempString as NSString).substring(from: 1)
        }
        
        // 5.获取RGB分别对应的16进制
        // r:FF g:00 b:22
        var range = NSRange(location: 0, length: 2)
        let rHex = (hexTempString as NSString).substring(with: range)
        range.location = 2
        let gHex = (hexTempString as NSString).substring(with: range)
        range.location = 4
        let bHex = (hexTempString as NSString).substring(with: range)
        
        // 6.将16进制转成数值 FF 22
        var r: UInt32 = 0
        var g: UInt32 = 0
        var b: UInt32 = 0
        Scanner(string: rHex).scanHexInt32(&r)
        Scanner(string: gHex).scanHexInt32(&g)
        Scanner(string: bHex).scanHexInt32(&b)
        
        self.init(r: CGFloat(r), g: CGFloat(g), b: CGFloat(b))
    }
    
}

// MARK: - 从颜色中取出RGB值
extension UIColor {
    func getRGBValue() -> (CGFloat, CGFloat, CGFloat) {
        
//        guard let cmps = cgColor.components else {
//            fatalError("重大错误! 请确定该颜色是通过RGB创建的")
//        }
//        return (cmps[0] * 255, cmps[1] * 255, cmps[2] * 255)
        
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        
        getRed(&red, green: &green, blue: &blue, alpha: nil)
        
        return (red * 255, green * 255, blue * 255)
    }
}




